package com.ibiz.znjd.znjd;


import com.ibiz.znjd.baidu.face.manager.APIService;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class FaceMatch {

    /**
     * 得分阈值
     */
    public static final double SCORE_THRESHOLD = 80;

    /**
     * 发送定位轨迹
     */
    public static void match(final Map<String, Object> resultMap, FaceMatchCallback callback){
        String matchUrl = "https://aip.baidubce.com/rest/2.0/face/v3/match?access_token="+ APIService.getInstance().getAccessToken();
        // 注册的图片
        String registerImage = (String) resultMap.get("register_image");
        String collectImage = (String) resultMap.get("collect_image");
        System.out.println("注册的图片"+registerImage);

        // 当前时间
        Date date = new Date();
        String strDateFormat = "yyyy-MM-dd HH:mm:ss";
        SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);
        String time = sdf.format(date);

        // 发起请求
        OkHttpClient client = new OkHttpClient();
        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        JSONArray array = new JSONArray();
        System.out.println("请求参数：");
        if(registerImage != null){
            System.out.println("register_image存在");
        }
        try {
            JSONObject json1 = new JSONObject();
            json1.put("image", registerImage);
            json1.put("image_type", "BASE64");
            array.put(json1);
            JSONObject json2 = new JSONObject();
            json2.put("image", collectImage);
            json2.put("image_type", "BASE64");
            array.put(json2);

        }catch (Exception e){
            e.printStackTrace();
        }
        RequestBody body = RequestBody.create(JSON, array.toString());
        Request request = new Request.Builder()
                .url(matchUrl)
                .post(body)
                .build();
        Call call = client.newCall(request);

        // 请求回调
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Map<String, Object> resultParams = new HashMap();
                resultParams.put("resultMsg", "连接失败");
                callback.onCallback(-1, resultParams);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Map<String, Object> resultParams = new HashMap();
                int code = 0;
                if(response.isSuccessful()){
                    String result = response.body().string();
                    System.out.println("对比请求结果："+result);
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        double score = jsonObject.getJSONObject("result").getDouble("score");
                        if(SCORE_THRESHOLD < score){
                            // 比对通过
                            code = 1;
                            resultParams.put("resultMsg", "验证通过");
                            resultParams.put("result_img", collectImage);
                        }else{
                            resultParams.put("resultMsg", "分数过低，验证失败");
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                        resultParams.put("resultMsg", "连接失败："+result);
                    }
                }else{
                    resultParams.put("resultMsg", "连接失败");
                }
                callback.onCallback(code, resultParams);
            }
        });
    }
}
